<template>
  <div class="editor-container">
    <el-card class="editor-card">
      <div class="editor-header">
        <el-input
            v-model="surveyTitle"
            placeholder="问卷标题"
            class="title-input"
            size="large"
        />
        <div class="header-actions">
          <el-button
              type="primary"
              @click="saveSurvey"
              icon="el-icon-check"
          >
            保存问卷
          </el-button>
          <el-button
              type="success"
              @click="previewSurvey"
              icon="el-icon-view"
          >
            预览
          </el-button>
        </div>
      </div>

      <el-input
          v-model="surveyDescription"
          placeholder="问卷描述（可选）"
          type="textarea"
          :rows="2"
          class="description-input"
      />

      <div class="question-list">
        <draggable
            v-model="survey.questions"
            item-key="id"
            handle=".drag-handle"
            @end="saveSurveys"
        >
          <template #item="{ element: question, index }">
            <div class="question-item">
              <div class="question-header">
                <el-icon class="drag-handle"><Menu /></el-icon>
                <span class="question-title">问题 {{ index + 1 }}</span>
                <el-select
                    v-model="question.type"
                    class="type-select"
                    @change="handleTypeChange(question)"
                >
                  <el-option label="单选题" value="radio" />
                  <el-option label="多选题" value="checkbox" />
                  <el-option label="文本题" value="text" />
                </el-select>
                <el-checkbox
                    v-model="question.required"
                    class="required-checkbox"
                >
                  必填
                </el-checkbox>
                <el-button
                    type="danger"
                    icon="Delete"
                    circle
                    @click="removeQuestion(question.id)"
                />
              </div>

              <el-input
                  v-model="question.title"
                  placeholder="输入问题内容"
                  class="question-content"
              />

              <div v-if="question.type !== 'text'" class="options-container">
                <div
                    v-for="(option, optIndex) in question.options"
                    :key="optIndex"
                    class="option-item"
                >
                  <el-icon><CirclePlus /></el-icon>
                  <el-input
                      v-model="question.options[optIndex]"
                      :placeholder="`选项 ${optIndex + 1}`"
                  />
                  <el-button
                      v-if="question.options.length > 1"
                      type="danger"
                      icon="Delete"
                      circle
                      @click="removeOption(question, optIndex)"
                  />
                </div>
                <el-button
                    type="primary"
                    plain
                    @click="addOption(question)"
                    icon="el-icon-plus"
                >
                  添加选项
                </el-button>
              </div>
            </div>
          </template>
        </draggable>
      </div>

      <div class="actions">
        <el-button-group>
          <el-button
              type="primary"
              @click="addQuestion('radio')"
              icon="el-icon-circle-check"
          >
            添加单选题
          </el-button>
          <el-button
              type="success"
              @click="addQuestion('checkbox')"
              icon="el-icon-finished"
          >
            添加多选题
          </el-button>
          <el-button
              type="info"
              @click="addQuestion('text')"
              icon="el-icon-edit"
          >
            添加文本题
          </el-button>
        </el-button-group>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import draggable from 'vuedraggable'
import { Menu, Delete, CirclePlus } from '@element-plus/icons-vue'
import { useSurveyStore } from '@/store/modules/survey.store'
import { ElMessage } from 'element-plus'

const route = useRoute()
const router = useRouter()
const surveyStore = useSurveyStore()

const surveyTitle = ref('未命名问卷')
const surveyDescription = ref('')

// 初始化问卷
onMounted(() => {
  const surveyId = route.params.id as string

  if (surveyId) {
    const survey = surveyStore.surveys.find(s => s.id === surveyId)
    if (survey) {
      surveyStore.currentSurvey = survey
      surveyTitle.value = survey.title
      surveyDescription.value = survey.description || ''
    } else {
      router.push({ name: 'create' })
    }
  } else {
    const newId = surveyStore.createSurvey('未命名问卷')
    router.push({ name: 'edit', params: { id: newId } })
  }
})

const survey = computed(() => surveyStore.currentSurvey || {
  id: '',
  title: '',
  description: '',
  questions: [],
  submissions: []
})

const handleTypeChange = (question: any) => {
  if (question.type !== 'text' && !question.options) {
    question.options = ['选项1', '选项2']
  }
}

const addQuestion = (type: 'radio' | 'checkbox' | 'text') => {
  surveyStore.addQuestion(type)
}

const removeQuestion = (questionId: string) => {
  surveyStore.removeQuestion(questionId)
}

const addOption = (question: any) => {
  if (question.options) {
    question.options.push(`选项 ${question.options.length + 1}`)
  } else {
    question.options = ['选项1', '选项2']
  }
}

const removeOption = (question: any, index: number) => {
  if (question.options && question.options.length > 1) {
    question.options.splice(index, 1)
  }
}

const saveSurvey = () => {
  if (surveyStore.currentSurvey) {
    surveyStore.currentSurvey.title = surveyTitle.value
    surveyStore.currentSurvey.description = surveyDescription.value
    surveyStore.saveSurveys()
    ElMessage.success('问卷已保存')
  }
}

const saveSurveys = () => {
  surveyStore.saveSurveys()
}

const previewSurvey = () => {
  if (surveyStore.currentSurvey) {
    saveSurvey()
    const id = surveyStore.currentSurvey.id
    window.open(`/survey/${id}`, '_blank')
  }
}
</script>

<style scoped>
.editor-container {
  padding: 20px;
}

.editor-card {
  border: none;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.editor-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  gap: 20px;
}

.title-input {
  flex: 1;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.description-input {
  margin-bottom: 30px;
}

.question-list {
  margin-bottom: 30px;
}

.question-item {
  background: #f9f9f9;
  padding: 20px;
  margin-bottom: 20px;
  border-radius: 6px;
  border: 1px solid #ebeef5;
  transition: all 0.3s;
}

.question-item:hover {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.question-header {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
  gap: 10px;
}

.drag-handle {
  cursor: move;
  color: #909399;
}

.drag-handle:hover {
  color: #409eff;
}

.question-title {
  font-weight: bold;
  color: #303133;
}

.type-select {
  width: 120px;
}

.required-checkbox {
  margin-left: 10px;
}

.question-content {
  margin-bottom: 15px;
}

.options-container {
  margin-left: 30px;
}

.option-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  gap: 10px;
}

.option-item > .el-icon {
  color: #909399;
}

.actions {
  margin-top: 20px;
  text-align: center;
}
</style>